package com.java.jiuyang.cloud.cleancode.errorhandle;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * @ClassName: CustomRestExceptionHandler
 * @Description:   使用@ControllerAdvice注解声明全局异常处理类，
 *                 @ExceptionHandler注解声明处理自定义异常，使用@Override覆盖通用异常处理
 *                 上述举例主要是针对restful接口的异常处理，如果想要在捕获异常后返回ModelAndView，而不是json消息，
 *                 可以让CustomRestExceptionHandler继承HandlerExceptionResolver，并覆盖resolveException()方法
 * @Version: v1.0.0
 * @Author: Fu Hao
 * @Date: 2019/11/12 0012 上午 9:13
 * Modification History:
 * Date           Author      Version     Description
 * -------------------------------------------------------------
 * 2019/11/12 0012        Fu Hao      v1.0.0         创建
 */

@Controller
public class CustomRestExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public ResponseEntity<Object> handleCustomerException(CustomException ex) {

        final ErrorDTO customeError = new ErrorDTO(ex.getErrorCode(), ex.getLocalizedMessage());

        return new ResponseEntity<Object>(customeError, new HttpHeaders(), ex.getHttpStatus());

    }

    //处理通用异常，这里举例说明如何覆盖处理 请求方法不支持的异常
    @Override
    protected ResponseEntity<Object> handleHttpRequestMethodNotSupported(HttpRequestMethodNotSupportedException ex,
                                                                         HttpHeaders headers, HttpStatus status, WebRequest request) {
        // TODO Auto-generated method stub
        final ErrorDTO customeError = new ErrorDTO(status.value(), "HttpRequestMethodNotSupported");
        return new ResponseEntity<Object>(customeError, new HttpHeaders(), status);
    }
}
